package com.rds.benchmark.command;

import com.rds.benchmark.CRC16;
import com.rds.benchmark.config.ArgvsConfig;
import com.rds.benchmark.util.Pxx;

import java.nio.charset.StandardCharsets;
import java.util.Random;

public abstract class CommandOperator {
    public final static int PXX_MAX = 8;
    public final static Pxx[] PXXES = new Pxx[PXX_MAX];

    private final static Random RANDOM = new Random();


    private static long PrintTimestamp = 0;

    static {
        for (int i = 0; i < PXX_MAX; ++i) {
            PXXES[i] = new Pxx(5000, 9000, 9500, 9900);
        }
    }

    public static void init_pxx() {
        for (int i = 0; i < PXX_MAX; ++i) {
            PXXES[i].init();
        }
    }

    public static String createKey(String prefix) {
        String key = prefix;

        if (ArgvsConfig.Start > 0 || ArgvsConfig.Stop < 16383) {
            int slot = CRC16.getSlot(key.getBytes(StandardCharsets.UTF_8));
            while (slot < ArgvsConfig.Start || slot > ArgvsConfig.Stop) {
                key = prefix + "-" + RANDOM.nextInt(100000);
                slot = CRC16.getSlot(key.getBytes(StandardCharsets.UTF_8));
            }
        }
        return key;
    }

    public static synchronized boolean needPrint() {
        long now = System.currentTimeMillis() / 1000;
        if (PrintTimestamp != now) {
            PrintTimestamp = now;
            return true;
        }
        return false;
    }
}
